package com.todod.base.module.base.util;

import cn.hutool.crypto.digest.MD5;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class MD5Encrypt {
    public static String toPinyin(String chinese) {
        StringBuilder pinyin = new StringBuilder();
        for (char character : chinese.toCharArray()) {
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(character);
            if (pinyinArray != null) {
                pinyin.append(pinyinArray[0]); // 取第一个拼音
            } else {
                pinyin.append(character); // 非汉字字符直接添加
            }
        }
        return pinyin.toString();
    }

    public static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String md5Encrypt(String example) {
        String pinyinName = toPinyin(example);
//        String md5Hash = md5(pinyinName);
        String md5Hex32 = MD5.create().digestHex(pinyinName);
        return md5Hex32.substring(8, 24); // 或者结合拼音和MD5值作为唯一标识
    }


//    //测试单元
//    public static void main(String[] args) {
//        String example = "123456";
//        String encrypted = md5Encrypt(example);
//
//        System.out.println("原始结果："+example);
//        System.out.println("最终加密结果：" + encrypted);
//    }
}




